package com.apollographql.apollo.internal;

import com.apollographql.apollo.ApolloSubscriptionCall;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.Subscription;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.api.internal.Utils;
import com.apollographql.apollo.cache.CacheHeaders;
import com.apollographql.apollo.cache.normalized.ApolloStore;
import com.apollographql.apollo.cache.normalized.Record;
import com.apollographql.apollo.cache.normalized.internal.ResponseNormalizer;
import com.apollographql.apollo.cache.normalized.internal.Transaction;
import com.apollographql.apollo.cache.normalized.internal.WriteableStore;
import com.apollographql.apollo.exception.ApolloCanceledException;
import com.apollographql.apollo.exception.ApolloNetworkException;
import com.apollographql.apollo.internal.CallState;
import com.apollographql.apollo.internal.subscription.ApolloSubscriptionException;
import com.apollographql.apollo.internal.subscription.SubscriptionManager;
import com.apollographql.apollo.internal.subscription.SubscriptionResponse;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;

public class RealApolloSubscriptionCall<T> implements ApolloSubscriptionCall<T> {
    private final ApolloStore apolloStore;
    private final ApolloSubscriptionCall.CachePolicy cachePolicy;
    private final Executor dispatcher;
    private final ApolloLogger logger;
    private final AtomicReference<CallState> state = new AtomicReference<>(CallState.IDLE);
    private final Subscription<?, T, ?> subscription;
    private SubscriptionManagerCallback<T> subscriptionCallback;
    private final SubscriptionManager subscriptionManager;

    public RealApolloSubscriptionCall(Subscription<?, T, ?> subscription2, SubscriptionManager subscriptionManager2, ApolloStore apolloStore2, ApolloSubscriptionCall.CachePolicy cachePolicy2, Executor dispatcher2, ApolloLogger logger2) {
        this.subscription = subscription2;
        this.subscriptionManager = subscriptionManager2;
        this.apolloStore = apolloStore2;
        this.cachePolicy = cachePolicy2;
        this.dispatcher = dispatcher2;
        this.logger = logger2;
    }

    @Override // com.apollographql.apollo.ApolloSubscriptionCall
    public void execute(final ApolloSubscriptionCall.Callback<T> callback) throws ApolloCanceledException {
        Utils.checkNotNull(callback, "callback == null");
        synchronized (this) {
            int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
            if (i == 1) {
                this.state.set(CallState.ACTIVE);
                if (this.cachePolicy == ApolloSubscriptionCall.CachePolicy.CACHE_AND_NETWORK) {
                    this.dispatcher.execute(new Runnable() {
                        /* class com.apollographql.apollo.internal.RealApolloSubscriptionCall.AnonymousClass1 */

                        public void run() {
                            Response<T> cachedResponse = RealApolloSubscriptionCall.this.resolveFromCache();
                            if (cachedResponse != null) {
                                callback.onResponse(cachedResponse);
                            }
                        }
                    });
                }
                SubscriptionManagerCallback<T> subscriptionManagerCallback = new SubscriptionManagerCallback<>(callback, this);
                this.subscriptionCallback = subscriptionManagerCallback;
                this.subscriptionManager.subscribe(this.subscription, subscriptionManagerCallback);
            } else if (i == 2) {
                throw new ApolloCanceledException();
            } else if (i == 3 || i == 4) {
                throw new IllegalStateException("Already Executed");
            } else {
                throw new IllegalStateException("Unknown state");
            }
        }
    }

    /* access modifiers changed from: package-private */
    /* renamed from: com.apollographql.apollo.internal.RealApolloSubscriptionCall$3  reason: invalid class name */
    public static /* synthetic */ class AnonymousClass3 {
        static final /* synthetic */ int[] $SwitchMap$com$apollographql$apollo$internal$CallState;

        static {
            int[] iArr = new int[CallState.values().length];
            $SwitchMap$com$apollographql$apollo$internal$CallState = iArr;
            try {
                iArr[CallState.IDLE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.CANCELED.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.TERMINATED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.ACTIVE.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable
    public void cancel() {
        synchronized (this) {
            int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
            if (i == 1) {
                this.state.set(CallState.CANCELED);
            } else if (!(i == 2 || i == 3)) {
                if (i == 4) {
                    try {
                        this.subscriptionManager.unsubscribe(this.subscription);
                    } finally {
                        this.state.set(CallState.CANCELED);
                        this.subscriptionCallback.release();
                    }
                } else {
                    throw new IllegalStateException("Unknown state");
                }
            }
        }
    }

    @Override // com.apollographql.apollo.ApolloSubscriptionCall
    public ApolloSubscriptionCall<T> clone() {
        return new RealApolloSubscriptionCall(this.subscription, this.subscriptionManager, this.apolloStore, this.cachePolicy, this.dispatcher, this.logger);
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable
    public boolean isCanceled() {
        return this.state.get() == CallState.CANCELED;
    }

    @Override // com.apollographql.apollo.ApolloSubscriptionCall
    public ApolloSubscriptionCall<T> cachePolicy(ApolloSubscriptionCall.CachePolicy cachePolicy2) {
        Utils.checkNotNull(cachePolicy2, "cachePolicy is null");
        return new RealApolloSubscriptionCall(this.subscription, this.subscriptionManager, this.apolloStore, cachePolicy2, this.dispatcher, this.logger);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void terminate() {
        synchronized (this) {
            int i = AnonymousClass3.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
            if (i != 1) {
                if (i != 2) {
                    if (i != 3) {
                        if (i == 4) {
                            this.state.set(CallState.TERMINATED);
                            this.subscriptionCallback.release();
                        } else {
                            throw new IllegalStateException("Unknown state");
                        }
                    }
                }
            }
            throw new IllegalStateException(CallState.IllegalStateMessage.forCurrentState(this.state.get()).expected(CallState.ACTIVE, CallState.CANCELED));
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Response<T> resolveFromCache() {
        ResponseNormalizer<Record> responseNormalizer = this.apolloStore.cacheResponseNormalizer();
        Response<T> cachedResponse = null;
        if (cachedResponse == null || cachedResponse.getData() == null) {
            this.logger.d("Cache MISS for subscription `%s`", this.subscription);
            return null;
        }
        this.logger.d("Cache HIT for subscription `%s`", this.subscription);
        return cachedResponse;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void cacheResponse(final SubscriptionResponse<T> networkResponse) {
        if (!networkResponse.cacheRecords.isEmpty() && this.cachePolicy != ApolloSubscriptionCall.CachePolicy.NO_CACHE) {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.RealApolloSubscriptionCall.AnonymousClass2 */

                public void run() {
                    try {
                        try {
                            RealApolloSubscriptionCall.this.apolloStore.publish((Set) RealApolloSubscriptionCall.this.apolloStore.writeTransaction(new Transaction<WriteableStore, Set<String>>() {
                                /* class com.apollographql.apollo.internal.RealApolloSubscriptionCall.AnonymousClass2.AnonymousClass1 */

                                public Set<String> execute(WriteableStore cache) {
                                    return cache.merge(networkResponse.cacheRecords, CacheHeaders.NONE);
                                }
                            }));
                        } catch (Exception e) {
                            RealApolloSubscriptionCall.this.logger.e(e, "Failed to publish cache changes for subscription `%s`", RealApolloSubscriptionCall.this.subscription);
                        }
                    } catch (Exception e2) {
                        RealApolloSubscriptionCall.this.logger.e(e2, "Failed to cache response for subscription `%s`", RealApolloSubscriptionCall.this.subscription);
                    }
                }
            });
        }
    }

    /* access modifiers changed from: private */
    public static final class SubscriptionManagerCallback<T> implements SubscriptionManager.Callback<T> {
        private RealApolloSubscriptionCall<T> delegate;
        private ApolloSubscriptionCall.Callback<T> originalCallback;

        SubscriptionManagerCallback(ApolloSubscriptionCall.Callback<T> originalCallback2, RealApolloSubscriptionCall<T> delegate2) {
            this.originalCallback = originalCallback2;
            this.delegate = delegate2;
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onResponse(SubscriptionResponse<T> response) {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                this.delegate.cacheResponse(response);
                callback.onResponse(response.response);
            }
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onError(ApolloSubscriptionException error) {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                callback.onFailure(error);
            }
            terminate();
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onNetworkError(Throwable t) {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                callback.onFailure(new ApolloNetworkException("Subscription failed", t));
            }
            terminate();
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onCompleted() {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                callback.onCompleted();
            }
            terminate();
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onTerminated() {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                callback.onTerminated();
            }
            terminate();
        }

        @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager.Callback
        public void onConnected() {
            ApolloSubscriptionCall.Callback<T> callback = this.originalCallback;
            if (callback != null) {
                callback.onConnected();
            }
        }

        /* access modifiers changed from: package-private */
        public void terminate() {
            RealApolloSubscriptionCall<T> delegate2 = this.delegate;
            if (delegate2 != null) {
                delegate2.terminate();
            }
        }

        /* access modifiers changed from: package-private */
        public void release() {
            this.originalCallback = null;
            this.delegate = null;
        }
    }
}
